package com.dabai.qrtools.ui;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import com.dabai.qrtools.R;
import com.dabai.qrtools.dialog.MdcDialog;
import com.dabai.qrtools.other.ImageUtils;
import com.dabai.qrtools.other.WatermarkUtils;
import com.dabai.qrtools.qrcode.QRCodeUtils;
import com.dabai.qrtools.utils.DabaiUtils;
import com.dabai.qrtools.utils.FileUtils;
import com.dabai.qrtools.utils.ThemeUtils;
import com.dabai.qrtools.utils.UriUtils;
import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.chip.Chip;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.textfield.TextInputLayout;

import java.io.IOException;
import java.util.Objects;
import java.util.Random;


public class WatermarkActivity extends AppCompatActivity {

    private Context context;
    private MaterialToolbar mToolbar;
    private ImageView mImageview1;
    private Bitmap photo;
    private int maxSide;
    private int side;
    private int alpha=100;
    private String qrContent = "二维码内容";

    private Direction direction = Direction.right2;

    private boolean transparent;
    private Bitmap result;
    private Chip mChipgroup1chip1;
    private Chip mChipgroup1chip2;
    private Chip mChipgroup1chip3;
    private Chip mChipgroup1chip4;
    private Chip mChipgroup1chip5;
    private Chip mChipgroup1chip6;
    private TextView mTip1;
    private CardView mTool1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_watermark);
        initViews();

        context = this;

        ThemeUtils.setAutoUiModeStatusBar(this, this);
        setSupportActionBar(mToolbar);
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);

        initListenerEvent();

    }

    private void initListenerEvent() {

        mChipgroup1chip1.setOnClickListener(v -> {
            if (photo == null) return;
            MdcDialog.showInputDialog(context, "设置二维码内容", qrContent, "内容", new MdcDialog.OnInputDialogButtonListener() {
                @Override
                public void confirm(DialogInterface dialog, String content) {
                    if (content.isEmpty()) return;

                    qrContent = content;
                    refQrContent();

                    dialog.dismiss();
                }

                @Override
                public void start(DialogInterface dialog, TextInputLayout textInputLayout) {

                }

                @Override
                public void cancel() {

                }
            }).getWindow().setWindowAnimations(R.style.DBAnim_Transitions_IOS);
        });

        mChipgroup1chip2.setOnClickListener(v -> {
            if (photo == null) return;

            new MaterialAlertDialogBuilder(this)
                    .setTitle("选择位置")
                    .setItems(new String[]{"左上角", "左下角", "中间", "右上角", "右下角"}, (dialog, which) -> {

                        if (which == 0) direction = Direction.left1;
                        if (which == 1) direction = Direction.left2;
                        if (which == 2) direction = Direction.center;
                        if (which == 3) direction = Direction.right1;
                        if (which == 4) direction = Direction.right2;

                        refQrContent();

                    }).show().getWindow().setWindowAnimations(R.style.DBAnim_Transitions_IOS);

        });

        mChipgroup1chip3.setOnClickListener(v -> {
            if (photo == null) return;

            MdcDialog.showSeekbarDialog(context, "设置二维码尺寸", maxSide, side, new MdcDialog.OnSeekbarDialogButtonListener() {
                @Override
                public void confirm(DialogInterface dialog, int progress) {
                    if (progress <= 0) return;

                    side = progress;
                    refQrContent();

                    dialog.dismiss();
                }

                @Override
                public void cancel() {

                }
            }).getWindow().setWindowAnimations(R.style.DBAnim_Transitions_IOS);
        });

        mChipgroup1chip4.setOnClickListener(v -> {
            if (photo == null) return;

            MdcDialog.showSeekbarDialog(context, "设置二维码透明度", 100, alpha, new MdcDialog.OnSeekbarDialogButtonListener() {
                @Override
                public void confirm(DialogInterface dialog, int progress) {

                    alpha = progress;
                    refQrContent();

                    dialog.dismiss();
                }

                @Override
                public void cancel() {

                }
            }).getWindow().setWindowAnimations(R.style.DBAnim_Transitions_IOS);
        });

        mChipgroup1chip5.setOnClickListener(v -> {
            if (photo == null) return;
            transparent = !transparent;
            refQrContent();
        });

        mChipgroup1chip6.setOnClickListener(v -> {
            if (photo == null) return;
            if (!transparent) {
                DabaiUtils.showToast(context, "必须处于透明底色");
                return;
            }

            String[] COLOR_VALUE = {"#000000","#ffffff", "#00BCD4", "#03A9F4", "#2196F3", "#3F51B5", "#673AB7", "#9C27B0", "#E91E63", "#F44336", "#FF9800", "#FFEB3B", "#4CAF50", "#FF5722", "#607D8B"};
            MdcDialog.showColorChooseDialog(context, "选择前景色", COLOR_VALUE, new MdcDialog.OnColorChooseListener() {
                @Override
                public void confirm(AlertDialog dialog, int color, String colorText) {
                    fColor = color;
                    refQrContent();

                    dialog.dismiss();
                }

                @Override
                public void parseError(AlertDialog dialog, String colorText) {

                }
            }).getWindow().setWindowAnimations(R.style.DBAnim_Transitions_IOS);

            refQrContent();
        });


    }

    enum Direction {
        center, left1, left2, right1, right2
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();

        if (itemId == android.R.id.home) {
            finish();
            return true;
        }

        if (itemId == R.id.choosePicture) {

            //打开手机中的相册
            Intent innerIntent = new Intent(Intent.ACTION_GET_CONTENT); //"android.intent.action.GET_CONTENT"
            innerIntent.setType("image/*");
            startActivityForResult(innerIntent, 401);

            return true;
        } else if (itemId == R.id.save) {
            if (result == null) return true;

            boolean isOk = FileUtils.saveBitmapToDCIM(context, result, "QRTools", "QRTools_" + new Random().nextInt(100000));
            DabaiUtils.showToast(context, isOk ? "保存成功" : "保存失败");

            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.watermark, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 401) {
                if (data != null) {

                    UriUtils uriUtils = new UriUtils(context, data.getData());
                    try {

                        photo = uriUtils.getBitmap();
                        maxSide = Math.min(photo.getHeight(), photo.getWidth());
                        side = maxSide / 5;

                        refQrContent();

                        mTip1.setVisibility(View.GONE);
                        mTool1.setVisibility(View.VISIBLE);

                    } catch (IOException e) {
                        DabaiUtils.showToast(context,"异常:"+e.getMessage());
                    }

                }
            }
        }

    }

    int fColor = Color.BLACK;

    private void refQrContent() {

        Bitmap water;
        if (transparent) {
            water = QRCodeUtils.createSimpleColorQrCodeBitmap(context, qrContent, side, fColor, Color.TRANSPARENT);
        } else {
            water = QRCodeUtils.createSimpleColorQrCodeBitmap(context, qrContent, side, Color.BLACK, Color.WHITE);
        }

        if (alpha<100){
            water = ImageUtils.getTransparentBitmap(water, alpha);
        }

        switch (direction) {
            case left1:
                result = WatermarkUtils.createWaterMaskLeftTop(context, photo, water, 0, 0);
                mImageview1.setImageBitmap(result);
                break;
            case left2:
                result = WatermarkUtils.createWaterMaskLeftBottom(context, photo, water, 0, 0);
                mImageview1.setImageBitmap(result);
                break;
            case center:
                result = WatermarkUtils.createWaterMaskCenter(photo, water);
                mImageview1.setImageBitmap(result);
                break;
            case right1:
                result = WatermarkUtils.createWaterMaskRightTop(context, photo, water, 0, 0);
                mImageview1.setImageBitmap(result);
                break;
            case right2:
                result = WatermarkUtils.createWaterMaskRightBottom(context, photo, water, 0, 0);
                mImageview1.setImageBitmap(result);
                break;
        }


    }


    private void initViews() {
        mToolbar = findViewById(R.id.toolBar);
        mImageview1 = findViewById(R.id.imageView1);

        mChipgroup1chip1 = findViewById(R.id.chipGroup1Chip1);
        mChipgroup1chip2 = findViewById(R.id.chipGroup1Chip2);
        mChipgroup1chip3 = findViewById(R.id.chipGroup1Chip3);
        mChipgroup1chip4 = findViewById(R.id.chipGroup1Chip4);
        mChipgroup1chip5 = findViewById(R.id.chipGroup1Chip5);
        mChipgroup1chip6 = findViewById(R.id.chipGroup1Chip6);
        mTip1 = findViewById(R.id.tip1);
        mTool1 = findViewById(R.id.tool1);
    }
}